import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateSceneFileRelationalDto } from './dto/create-scene_file_relational.dto';
import { UpdateSceneFileRelationalDto } from './dto/update-scene_file_relational.dto';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { SceneFileRelational } from './entities/scene_file_relational.entity';
import { FileListService } from '../file-list/file-list.service';

@Injectable()
export class SceneFileRelationalService {
  constructor(
    @InjectRepository(SceneFileRelational)
    private readonly sceneFileRelationalRepository: Repository<SceneFileRelational>,
    private readonly fileListService: FileListService,
  ) {}
  async create(createSceneFileRelationalDto: CreateSceneFileRelationalDto) {
    const searchRes = await this.sceneFileRelationalRepository.findOne({
      where: {
        scene_id: createSceneFileRelationalDto.scene_id,
        file_id: createSceneFileRelationalDto.file_id,
      },
    });
    if (searchRes) {
      return '已经添加';
    } else {
      const sceneFileRelational = this.sceneFileRelationalRepository.create(
        createSceneFileRelationalDto,
      );
      this.sceneFileRelationalRepository.insert(sceneFileRelational);
    }
  }

  async findAll(): Promise<SceneFileRelational[]> {
    return this.sceneFileRelationalRepository.find();
  }

  async findOne(id: string): Promise<SceneFileRelational> {
    return this.sceneFileRelationalRepository.findOne({ where: { id: id } });
  }

  async findBySceneId(scene_id: string): Promise<SceneFileRelational[]> {
    return this.sceneFileRelationalRepository.find({
      where: { scene_id: scene_id },
      select: ['file_id'],
    });
  }

  async getFileTypeBySceneId(scene_id: string, fileType: string) {
    const fileList = await this.sceneFileRelationalRepository.find({
      where: { scene_id: scene_id },
      select: ['file_id', 'used', 'id'],
    });
    if (fileList.length === 0) {
      return [];
    }
    const fileIdList = fileList.map((item) => item.file_id);
    let fileTypeList: any = await this.fileListService.getByTypeAndFileIds(
      fileType,
      fileIdList,
    );
    // 合并used字段到fileTypeList
    fileTypeList = fileTypeList.map((file) => {
      // 查找file对应的used值
      const foundFile = fileList.find((item) => item.file_id === file.id);
      return {
        ...file,
        used: foundFile ? foundFile.used : false, // 如果没有找到，默认used为false
        scenceToFileId: foundFile ? foundFile.id : '',
      };
    });
    return fileTypeList;
  }

  async update(
    id: string,
    updateSceneFileRelationalDto: UpdateSceneFileRelationalDto,
  ): Promise<SceneFileRelational | string> {
    const oldItem = await this.sceneFileRelationalRepository.findOne({
      where: { id },
    });

    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    const updateSceneFileRelational = this.sceneFileRelationalRepository.merge(
      oldItem,
      updateSceneFileRelationalDto,
    );

    await this.sceneFileRelationalRepository.save(updateSceneFileRelational);

    // 返回更新后的实体或其他有用的信息
    return updateSceneFileRelational;
  }

  async updateScenceToFileRelationItemByFileIdScenceId(
    updateSceneFileRelationalDto: UpdateSceneFileRelationalDto,
  ) {
    const oldItem = await this.sceneFileRelationalRepository.findOne({
      where: {
        scene_id: updateSceneFileRelationalDto.scene_id,
        file_id: updateSceneFileRelationalDto.file_id,
      },
    });
    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    const updateSceneFileRelational = this.sceneFileRelationalRepository.merge(
      oldItem,
      updateSceneFileRelationalDto,
    );

    await this.sceneFileRelationalRepository.save(updateSceneFileRelational);

    // 返回更新后的实体或其他有用的信息
    return updateSceneFileRelational;
  }

  async remove(id: string) {
    const result = await this.sceneFileRelationalRepository.delete({
      id: id,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async removeRelationByFileId(fileId: string) {
    const result = await this.sceneFileRelationalRepository.delete({
      file_id: fileId,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async removeBySceneId(scenceId: string) {
    const result = await this.sceneFileRelationalRepository.delete({
      scene_id: scenceId,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }

  async getFilesIsUsedByScence(param: { filesArray: any[]; scenceId: string }) {
    const fileList = await this.sceneFileRelationalRepository.find({
      where: { scene_id: param.scenceId },
      select: ['file_id', 'used', 'id'],
    });
    param.filesArray = param.filesArray.map((file) => {
      const foundFile = fileList.find((item) => item.file_id === file.id);
      return {
        ...file,
        used: foundFile ? foundFile.used : false, // 如果没有找到，默认used为false
        scenceToFileId: foundFile ? foundFile.id : '',
      };
    });
    return param.filesArray;
  }

  async getScenceToFileRelationItemByFileIdScenceId(param: {
    file_id: string;
    scence_id: string;
  }) {
    return this.sceneFileRelationalRepository.findOne({
      where: { file_id: param.file_id, scene_id: param.scence_id },
    });
  }

  async getIsUsedByFileId(fileuuid: string) {
    const findRes = await this.sceneFileRelationalRepository.find({
      where: { file_id: fileuuid },
    });

    // 检查 findRes 数组中是否至少有一个对象的 used 属性为 true
    return await findRes.some((item) => item.used === true);
  }
}
